///<reference path="../Content/ext/adapter/ext/ext-base.js" />
///<reference path="../Content/ext/ext-all-debug.js" />

Ext.BLANK_IMAGE_URL = '/Content/ext/resources/images/default/s.gif';

Docs = {};

ApiPanel = function() {
    ApiPanel.superclass.constructor.call(this, {
        id:'api-tree',
        region:'west',
        split:true,
        header: false,
        width: 280,
        minSize: 175,
        maxSize: 500,
        collapsible: true,
        margins:'0 0 5 5',
        cmargins:'0 0 0 0',
        rootVisible:false,
        lines:false,
        autoScroll:true,
        animCollapse:false,
        animate: false,
        collapseMode:'mini',
        loader: new Ext.tree.TreeLoader({
			preloadChildren: true,
			clearOnLoad: false
		}),
        root: new Ext.tree.AsyncTreeNode({
            text:'Ext JS',
            id:'root',
            expanded:true,
            children:[Docs.classData]
         }),
        collapseFirst:false
    });
    // no longer needed!
    //new Ext.tree.TreeSorter(this, {folderSort:true,leafAttr:'isClass'});

    this.getSelectionModel().on('beforeselect', function(sm, node){
        return node.isLeaf();
    });
};


////扩展
Ext.extend(ApiPanel, Ext.tree.TreePanel, {
    initComponent: function(){
        this.hiddenPkgs = [];
        Ext.apply(this, {
            tbar:[ ' ',
			new Ext.form.TextField({
				width: 200,
				emptyText:'Find a Class',
                enableKeyEvents: true,
				listeners:{
					render: function(f){
                    	this.filter = new Ext.tree.TreeFilter(this, {
                    		clearBlank: true,
                    		autoClear: true
                    	});
					},
                    keydown: {
                        fn: this.filterTree,
                        buffer: 350,
                        scope: this
                    },
                    scope: this
				}
			}), ' ', ' ',
			{
                iconCls: 'icon-expand-all',
				tooltip: 'Expand All',
                handler: function(){ this.root.expand(true); },
                scope: this
            }, '-', {
                iconCls: 'icon-collapse-all',
                tooltip: 'Collapse All',
                handler: function(){ this.root.collapse(true); },
                scope: this
            }]
        })
        ApiPanel.superclass.initComponent.call(this);
    },
	filterTree: function(t, e){
		var text = t.getValue();
		Ext.each(this.hiddenPkgs, function(n){
			n.ui.show();
		});
		if(!text){
			this.filter.clear();
			return;
		}
		this.expandAll();
		
		var re = new RegExp('^' + Ext.escapeRe(text), 'i');
		this.filter.filterBy(function(n){
			return !n.attributes.isClass || re.test(n.text);
		});
		
		// hide empty packages that weren't filtered
		this.hiddenPkgs = [];
                var me = this;
		this.root.cascade(function(n){
			if(!n.attributes.isClass && n.ui.ctNode.offsetHeight < 3){
				n.ui.hide();
				me.hiddenPkgs.push(n);
			}
		});
	},//当选择主窗口tab时，左边菜单自动选中
    selectClass : function(cls){
        if(cls){
            var parts = cls.split('.');
            var last = parts.length-1;
            var res = [];
            var pkg = [];
            for(var i = 0; i < last; i++){ // things get nasty - static classes can have .
                var p = parts[i];
                var fc = p.charAt(0);
                var staticCls = fc.toUpperCase() == fc;
                if(p == 'Ext' || !staticCls){
                    pkg.push(p);
                    res[i] = 'pkg-'+pkg.join('.');
                }else if(staticCls){
                    --last;
                    res.splice(i, 1);
                }
            }
            res[last] = cls;
        
        }
    }
});


DocPanel = Ext.extend(Ext.Panel, {
    closable: true,
    autoScroll: true,

    initComponent: function() {
        var ps = this.cclass.split('.');
        this.title = ps[ps.length - 1];

        DocPanel.superclass.initComponent.call(this);
    }


});


MainPanel = function(){
	
	this.searchStore = new Ext.data.Store({
        reader: new Ext.data.JsonReader({
	            root: 'data'
	        }, 
			['cls', 'member', 'type', 'doc']
		),
		baseParams: {},
        listeners: {
            'beforeload' : function(){
                this.baseParams.qt = Ext.getCmp('search-type').getValue();
            }
        }
    }); 
	
    MainPanel.superclass.constructor.call(this, {
        id:'doc-body',
        region:'center',
        margins:'0 5 5 0',
        resizeTabs: true,
        minTabWidth: 135,
        tabWidth: 135,
        plugins: new Ext.ux.TabCloseMenu(),
        enableTabScroll: true,
        activeTab: 0,

        items: {
            id:'welcome-panel',
            title: 'Welcome',
            autoLoad: { url: '/Home/Welcome', scope: this, scripts: true },
            iconCls:'icon-docs',
            autoScroll: true
        }
    });
};

Ext.extend(MainPanel, Ext.TabPanel, {

    initEvents: function() {
        MainPanel.superclass.initEvents.call(this);
        this.body.on('click', this.onClick, this);
    },

    onClick: function(e, target) {
        if (target = e.getTarget('a:not(.exi)', 3)) {
            var cls = Ext.fly(target).getAttributeNS('ext', 'cls');
            e.stopEvent();
            if (cls) {
                var member = Ext.fly(target).getAttributeNS('ext', 'member');
                this.loadClass(target.href, cls, member);
            } else if (target.className == 'inner-link') {
                this.getActiveTab().scrollToSection(target.href.split('#')[1]);
            } else {
                window.open(target.href);
            }
        } else if (target = e.getTarget('.micon', 2)) {
            e.stopEvent();
            var tr = Ext.fly(target.parentNode);
            if (tr.hasClass('expandable')) {
                tr.toggleClass('expanded');
            }
        }
    },
    ////载入内容现在在tab上
    loadClass: function(href, cls, member) {
    var id = 'docs-' + cls;
        ////判断页面是否已经打开
        var tab = this.getComponent(id);
        if (tab) {
            this.setActiveTab(tab);
            if (member) {
                tab.scrollToMember(member);
            }
        } else {
        ////自动载入配置
            var autoLoad = { url: href,scripts: true };
            if (member) {
                autoLoad.callback = function() {
                    Ext.getCmp(id).scrollToMember(member);
                }
            }
            var p = this.add(new DocPanel({
                id: id,
                cclass: cls,
                autoLoad: autoLoad,
                iconCls: Docs.icons[cls]
            }));

            this.setActiveTab(p);

//            p.load({
//                url: href,
//                method: 'get',
//                scope: this, // optional scope for the callback
//                discardUrl: true,
//                nocache: true,
//                text: "页面加载中,请稍候……",
//                scripts: true
//            });

        }
    }
});


Ext.onReady(function(){

    Ext.QuickTips.init();
    
    var api = new ApiPanel();
    var mainPanel = new MainPanel();
    
    
    ////菜单项点击触发主页面载入制定内容
    api.on('click', function(node, e){
         if(node.isLeaf()){
            e.stopEvent();
            mainPanel.loadClass(node.attributes.href, node.id);
         }
    });

    mainPanel.on('tabchange', function(tp, tab){
        api.selectClass(tab.cclass); 
    });

    var viewport = new Ext.Viewport({
        layout:'border',
        items:[ {
            cls: 'docs-header',
            height: 44,
            region:'north',
            xtype:'box',
            el:'header',
            border:false,
            margins: '0 0 5 0'
        }, api, mainPanel ]
    });

    ///展开的树节点
    api.expandPath('/root/apidocs');

    viewport.doLayout();
	
	setTimeout(function(){
        Ext.get('loading').remove();
        Ext.get('loading-mask').fadeOut({remove:true});
    }, 250);
	
});

